package com.www.applyword.ui.chat;

import android.content.Intent;
import android.os.Environment;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.ResultBean;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;

/**
 * author : huang
 * date   : 2019/11/9 0009 16:30
 * version: 1.0
 */
public class FabuDynaminActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate {

    public static final int RC_CHOOSE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO2 = 11;
    public static final int RC_PHOTO_PREVIEW = 2;
    public static final int RC_PHOTO_PREVIEW2 = 22;

    @BindView(R.id.et)
    EditText et;
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.snpl_moment_add_photos)
    BGASortableNinePhotoLayout mPhotosSnpl;

    private List<String> data;
    private String photosUrl = "";
    private int i = 0;
    private ArrayList<String> list_path = new ArrayList<>();


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.fabu_activity);
        setTitle("发布");
        setRringTitle("发送");
        mPhotosSnpl.setDelegate(this);
        tv_right.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(et.getText().toString().trim()) || (mPhotosSnpl != null && mPhotosSnpl.getData().size() > 0)) {
               // Utils.showToastSafe("请发布内容");
               // return;
                if (Utils.isFastClick())
                    submitImg();
            }else {
                Utils.showToastSafe("请先添加发布内容或图片");
            }
        });
    }

    private void submitImg() {
        list_path.clear();
        data = mPhotosSnpl.getData();
        if (data.size()>0) {
            for (String datum : data) {
                HttpClient.postImg(FabuDynaminActivity.this, Constants.UPLOADFORUM, new File(datum), new CallBack<List<String>>() {
                    @Override
                    public void onSuccess(List<String> list) {
                        list_path.add(list.get(0));
                        if (data.size() == list_path.size()) {
                            sendForum();
                        }
                    }
                });
            }
        }else {
            sendForum();
        }
    }

    private void sendForum() {
        Map<String, Object> params = new HashMap<>();
        if (data.size()>0) {
            for (String s : list_path) {
                photosUrl += s + ",";
            }
            params.put("Forum_Img",photosUrl.substring(0,photosUrl.length()-1));
        }else {
            params.put("Forum_Img","");
        }
        params.put("Forum_Title","");
        params.put("Forum_Content",et.getText().toString().trim());
        params.put("Forum_UserID", SPUtil.getString(Constants.USERID));
        params.put("Forum_Address",SPUtil.getString("city"));
        params.put("Forum_Lng","0");
        params.put("Forum_Lat","0");
        HttpClient.post(FabuDynaminActivity.this, Constants.ADDFORUM, params, new CallBack<ResultBean>() {
            @Override
            public void onSuccess(ResultBean list) {
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.FANBU);
                EventBus.getDefault().post(messageEvent);
                finish();
            }
        });
    }

    @Override
    protected void loadData() {
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Editable editable = et.getText();
                int len = editable.length();
                //显示还可以输入多少字
                tv.setText(len + "" + "/200");
                if (len > 200) {
                    Utils.showToastSafe("超出字数限制");
                    int selEndIndex = Selection.getSelectionEnd(editable);
                    String str = editable.toString();
                    //截取新字符串
                    String newStr = str.substring(0, 500);
                    et.setText(newStr);
                    editable = et.getText();

                    //新字符串的长度
                    int newLen = editable.length();
                    //旧光标位置超过字符串长度
                    if (selEndIndex > newLen) {
                        selEndIndex = editable.length();
                    }
                    //设置新光标所在的位置
                    Selection.setSelection(editable, selEndIndex);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    private void choicePhotoWrapper() {
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "job");

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();
        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        if (mPhotosSnpl.getData().size() > 0) {
            mPhotosSnpl.removeItem(position);
        }
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) { //拍照
            mPhotosSnpl.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));

        } else if (requestCode == RC_PHOTO_PREVIEW) {   //相册
            mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedPhotos(data));
        }
    }
}
